﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using log4net;
using Newtonsoft.Json;

namespace Analyze.Service
{
    class BosonNlpApi
    {
        public static readonly string SegmentUrl = "http://api.bosonnlp.com/tag/analysis?space_mode=0&oov_level=3&t2s=1";
        public static readonly string KeywordUrl = "http://api.bosonnlp.com/keywords/analysis";
        private static readonly ILog Log = LogManager.GetLogger(typeof(BosonNlpApi));
        
        private static string GetSegmResultJson(string[] contents)
        {
            var request = GetRequest(SegmentUrl);

            Stream outputStream = request.GetRequestStream();
            string data = null;
            if (contents.Length > 1)
            {
                data = JsonConvert.SerializeObject(contents.ToList());
            }
            else
            {
                data = JsonConvert.SerializeObject(contents[0]);
            }

            var bytes = Encoding.UTF8.GetBytes(data);
            outputStream.Write(bytes, 0, bytes.Length);
            outputStream.Close();

            HttpWebResponse response = null;
            try
            {
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (Exception e)
            {
                Log.Error(e);
                try
                {
                    response = (HttpWebResponse)request.GetResponse();
                }
                catch (Exception ex)
                {
                    Log.Error(ex);
                    throw;
                }
            }

            Stream responseStream = response.GetResponseStream();
            StreamReader streamReader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
            string retString = streamReader.ReadToEnd();
            streamReader.Close();
            responseStream.Close();
            return retString;
        }

        private static HttpWebRequest GetRequest(string url)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = WebRequestMethods.Http.Post;
            request.ContentType = "application/json";
            request.Accept = "application/json";
            request.Headers.Add("X-Token", "bXPGTylg.21756.GNx7PraknITE");
            return request;
        }

        public static List<List<string>> GetWords(string[] contents)
        {
            var json = GetSegmResultJson(contents);
            List<Segm> segm = JsonConvert.DeserializeObject<List<Segm>>(json);
            return segm.Select(m =>
            {
                var list = new List<string>();
                for (var i = 0; i < m.word.Count; i++)
                {
                    var isNoun = m.tag[i].StartsWith("n");
                    if (isNoun)
                    {
                        list.Add(m.word[i]);
                    }
                }
                return list;
            }).ToList(); 
        }

        public static List<List<Object>> GetKeywords(string content)
        {
            string keywordJson = GetKeywordJson(content);
            return JsonConvert.DeserializeObject<List<List<Object>>>(keywordJson);
        }
        
        private static string GetKeywordJson(string content)
        {
            var request = GetRequest(KeywordUrl);

            Stream outputStream = request.GetRequestStream();
            string data = null;
            data = JsonConvert.SerializeObject(content);
            var bytes = Encoding.UTF8.GetBytes(data);
            outputStream.Write(bytes, 0, bytes.Length);
            outputStream.Close();

            HttpWebResponse response = null;
            try
            {
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (Exception e)
            {
                Log.Error(e);
                try
                {
                    response = (HttpWebResponse)request.GetResponse();
                }
                catch (Exception ex)
                {
                    Log.Error(ex);
                    throw;
                }
            }

            Stream responseStream = response.GetResponseStream();
            StreamReader streamReader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
            string retString = streamReader.ReadToEnd();
            streamReader.Close();
            responseStream.Close();
            return retString;
        }
        
        public class Segm
        {
            public List<string> word;
            public List<string> tag;
        }
    }
}